package com.atguigu.spzx.product.manager;

import com.atguigu.spzx.common.utils.BeanUtils;
import com.atguigu.spzx.product.entity.Category;
import com.atguigu.spzx.product.mapper.CategoryMapper;
import com.atguigu.spzx.product.vo.CategoryTreeQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * CategoryCacheManager
 * </p>
 *
 * @author flyduck
 * @since 2023/11/4
 */
@Component
public class CategoryCacheManager {

    @Autowired
    private CategoryMapper categoryMapper;


    /**
     * 所有一级分类
     * @return
     */
    @Cacheable(value = "category" , key = "'one'")
    public List<Category> getOneLevelCategoryList() {
        return categoryMapper.getCategoryListByParentId(0L);
    }

    /**
     * 获取分类树
     * @return
     */
    @Cacheable(value = "category" , key = "'all'")
    public List<CategoryTreeQueryVo> findCategoryTree() {
        //1.查询所有的分类
        List<Category> list = categoryMapper.selectList(null);
        List<CategoryTreeQueryVo> allCategoryList = BeanUtils.toBeanList(list, CategoryTreeQueryVo.class);

        //2.遍历分类找到所有的一级分类
        List<CategoryTreeQueryVo> oneCategoryList = allCategoryList.stream()
                .filter(category -> category.getParentId().longValue() == 0)
                .collect(Collectors.toList());

        //3.遍历一级分类找到二级分类，将二级分类封装到一级分类的children
        oneCategoryList.forEach(oneCategory -> {
            List<CategoryTreeQueryVo> twoCategoryList = allCategoryList.stream()
                    .filter(category -> category.getParentId().equals(oneCategory.getId()))
                    .collect(Collectors.toList());
            oneCategory.setChildren(twoCategoryList);

            //4.遍历二级分类找到三级分类，将三级分类封装到二级分类的children
            twoCategoryList.forEach(twoCategory -> {
                List<CategoryTreeQueryVo> threeCategoryList = allCategoryList.stream()
                        .filter(category -> category.getParentId().equals(twoCategory.getId()))
                        .collect(Collectors.toList());
                twoCategory.setChildren(threeCategoryList);
            });

        });
        return oneCategoryList;

    }
}
